package com.gpframework.module.controller.system;

import com.gpframework.common.constant.Constants;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.domain.entity.SysDept;
import com.gpframework.common.core.domain.entity.SysMenu;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.domain.model.LoginBody;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.ServletUtils;
import com.gpframework.module.common.service.ICommonPhoneMsgTemplateService;
import com.gpframework.module.common.service.ICommonWxUserService;
import com.gpframework.module.core.LoginUser;
import com.gpframework.module.module.domain.req.BrandStoreReq;
import com.gpframework.module.module.domain.vo.BrandInfoVo;
import com.gpframework.module.module.domain.vo.BrandStoreVo;
import com.gpframework.module.module.domain.vo.UserStoreVo;
import com.gpframework.module.module.service.IBrandInfoService;
import com.gpframework.module.module.service.IBrandStoreService;
import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.service.SysLoginService;
import com.gpframework.module.service.SysPermissionService;
import com.gpframework.module.service.TokenService;
import com.gpframework.module.service.system.ISysDeptService;
import com.gpframework.module.service.system.ISysMenuService;
import com.gpframework.module.service.system.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @Author gpframework
 */
@Api(tags = "系统登录")
@SuppressWarnings({"rawtypes"})
@RestController
@Slf4j
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IBrandStoreService brandStoreService;

    @Autowired
    private ICommonPhoneMsgTemplateService iCommonPhoneMsgTemplateService;

    @Autowired
    private IBrandInfoService brandInfoService;


    /**
     * redis缓存
     */
    @Autowired
    private RedisCache redisCache;


    @Autowired
    private ICommonWxUserService commonWxUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public Map login(@RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getBrandId());
        ajax.put(Constants.TOKEN, token);
        // 判断用户是否在职状态，如果离职拒绝登录系统
        SysUser sysUser = userService.selectUserByUserName(loginBody.getUsername(), loginBody.getBrandId());
        //if (!StringUtils.isEmpty(sysUser)) {
        //    UserEmployees userEntryStatus = userService.getUserEntryStatus(sysUser.getBrandUserId());
        //    if (!StringUtils.isEmpty(userEntryStatus)) {
        //        throw new BaseException("对不起，您的账号：" + loginBody.getUsername() + " 没有登录权限");
        //    }
        //}
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public Map getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        SysUser user1 = userService.getbyBrandUserId(loginUser.getUser().getBrandUserId());
        user.setConfiguration(user1.getConfiguration());
        //查询门店信息
        BrandStoreReq brandStoreReq = new BrandStoreReq();
        brandStoreReq.setBrandId(user.getBrandId());
        brandStoreReq.setStoreId(user.getStoreId());
        brandStoreReq.setUserName(user.getUserName());
        BrandStoreVo storeVo = brandStoreService.get(brandStoreReq);
        //获取部门信息
        List<SysDept> sysDeptList = sysDeptService.findByBrandUserId(user.getBrandUserId());
        if (StringUtil.isNotEmpty(sysDeptList) && sysDeptList.size() > 0) {
            user.setDept(sysDeptList.get(0));
        }
        if (!StringUtils.isEmpty(storeVo)) {
            user.setStoreAdmin(Integer.parseInt(YesNoEnum.NO.getKey()));
            //更新登录用户缓存信息
            tokenService.setLoginUser(loginUser);
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> ajax = new HashMap<>();
        BrandInfoVo brandInfoVo = brandInfoService.getBrandInfo(user.getBrandId());
        if (StringUtil.isNotEmpty(brandInfoVo)) {
            ajax.put("logo", brandInfoVo.getBrandLogo());
        }
        ajax.put("code", 200);
        ajax.put("msg", "操作成功");
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters(Long brandId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getBrandUserId(), user);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取用户品牌账号列表
     *
     * @param brandStoreReq 获取用户门店账号列表
     * @return 结果
     */
    @ApiOperation("获取用户品牌账号列表")
    @PostMapping("/getUserBrandList")
    public AjaxResult<UserStoreVo> getUserBrandList(@RequestBody BrandStoreReq brandStoreReq) {
        if (StringUtil.isEmpty(brandStoreReq.getStoreMobile())) {
            return AjaxResult.parameterError();
        }
        List<UserStoreVo> userStoreList = brandInfoService.getUserBrandList(brandStoreReq);
        return AjaxResult.success(userStoreList);
    }
}
